<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" v-model="queryForm" :inline="true">
						<el-form-item>
							<el-button v-if="$hasPer('PutStorage1:add')" @click="nodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('PutStorage7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="业务类型" align="center">
											<el-table-column :show-overflow-tooltip="true" min-width="120" align="center">
												<template #header>
													<SearchModel typeId="value" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.value }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="危化品名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="name" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.name }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="友商名称" align="center">
											<el-table-column :show-overflow-tooltip="true" min-width="120" align="center">
												<template #header>
													<SearchModel typeId="v_ProvideName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.v_ProvideName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="90" :show-overflow-tooltip="true" prop="empName" label="仓管员姓名1" align="center" />
										<el-table-column min-width="90" :show-overflow-tooltip="true" prop="empName2" label="仓管员姓名2" align="center" />

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="inOrOut" label="状态" align="center">
											<template #default="scope">
												<span v-if="scope.row.inOrOut == 1">在库</span>
												<span v-else>出库</span>
											</template>
										</el-table-column>
										<!-- <el-table-column min-width="120" :show-overflow-tooltip="true" prop="BoundOrderId" label="入库单号" align="center" /> -->
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="productBatchId" label="产品批号" align="center" />

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="inBoundQuantity" label="入库数量" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="locationDetailName" label="存储位置" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="boundDate" label="入库日期"  :formatter="formatDate" align="center" />

										<el-table-column min-width="180" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" align="center" fixed="right">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>

												<template #default="scope">
													<div class="operate-s">
														<el-button v-if="$hasPer('PutStorage2:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>
														<el-button v-if="$hasPer('PutStorage3:delete')" @click="deleteHandle(scope.row.n_Id, getData)" class="icon-e" icon="ele-Delete" size="small" text type="danger">
															删除
														</el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="saveId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form label-width="100px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="BoundOrderId" label="入库订单id">
							<el-input v-model="ruleForm.BoundOrderId" disabled placeholder="请选择入库订单id" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="businessType" label="业务类型">
							<el-select v-model="ruleForm.businessType" placeholder="请选择业务类型" style="width: 100%">
								<el-option v-for="item in options4" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="!saveId">
						<el-form-item prop="providerId" label="供应商">
							<el-select v-model="ruleForm.providerId" @change="selectProviderId" placeholder="请选择供应商" style="width: 100%">
								<el-option v-for="item in options6" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="boundDate" label="入库日期">
							<el-date-picker style="width: 100%" format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="ruleForm.boundDate" type="date" placeholder="请选择入库日期" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="warehouseAdministratorId" label="仓管员1">
							<el-select v-model="ruleForm.warehouseAdministratorId" placeholder="请选择仓管员1" style="width: 100%">
								<el-option v-for="item in options5" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="warehouseAdministrator2Id" label="仓管员2">
							<el-select v-model="ruleForm.warehouseAdministrator2Id" placeholder="请选择仓管员2" style="width: 100%">
								<el-option v-for="item in options5" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="productBatchId" label="产品批号">
							<el-input v-model="ruleForm.productBatchId" placeholder="请输入产品批号" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="chemicalId" label="危化品">
							<el-select v-model="ruleForm.chemicalId" placeholder="请选择危化品" style="width: 100%" @change="changeFun1">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="inBoundQuantity" label="数量">
							<el-input v-model="ruleForm.inBoundQuantity" placeholder="请输入数量" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item v-if="ruleForm.chemicalId" prop="location" label="存储位置">
							<el-select v-model="ruleForm.location" placeholder="请选择存储位置" style="width: 100%">
								<el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<template v-if="!saveId">
					<el-divider content-position="left"> 附件查询 </el-divider>
					<el-table :data="fileData" style="width: 100%" element-loading-background="rgba(0, 0, 0, 0.5)" border>
					<el-table-column type="index" label="序号" min-width="60" align="center" />
					<el-table-column prop="name" label="类型" min-width="120" align="center" :show-overflow-tooltip="true" />
					<el-table-column prop="createdUserName" label="上传人" min-width="100" align="center" :show-overflow-tooltip="true" />
					<el-table-column prop="createdTime" label="上传时间" min-width="120" align="center" :show-overflow-tooltip="true" />
					<el-table-column fixed="right" prop="operation" label="操作" show-overflow-tooltip min-width="140" align="center">
						<template #default="scope">
							<el-button @click="viewClick(scope.row)" class="icon-e" text type="success">预览</el-button>
							<el-button @click="downClick(scope.row)" class="icon-e" text type="warning">下载</el-button>
							<el-button @click="delClick(scope.row.id)" class="icon-e" text type="danger">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				</template>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef, getData)">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, reactive } from 'vue';
import getTableData from '/@/utils/getTableData';
import { ElMessageBox, ElMessage, FormInstance, dayjs } from 'element-plus';
import {
	getStocksDangerousChemicalsInApi,
	deleteStocksDangerousChemicalsInApi,
	addPutDangerousChemicalsInApi,
	queryStocksDangerousChemicalsInApi1,
	updateStocksDangerousChemicalsInApi,
	queryStocksDangerousChemicalsInApi,
	getChemicalsCargoManagerApi,
	downloadFileApi
} from '/@/api/sms/HazardousChemicalsInterface';
import { sysDictDataList, sysFileInfoPreviewBase64 } from '/@/api/centerControl/pubilc';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
import { Local } from '/@/utils/storage';
import { sysFileInfoDelete } from '/@/api/centerControl/oms';
// import { Local } from '/@/utils/storage';
// import { accessTokenKey } from '/@/utils/axios-utils';
export default defineComponent({
	components: {
		SearchModel,
	},
	setup() {
		/***** 变量 *****/
		let searchObj: any = reactive({
			InOrOut: 1,
		});
		const fileData: any = ref([]);
		const transferVal = ref(); // 需要查询的值
		const showDialogVisible = ref(false);
		let ruleForm: any = reactive({
			chemicalId: '', //危化品id
			boundDate: '', //变更库日期
			// warehouseAdministrator: '', //仓管员名称
			warehouseAdministratorId: '', // 仓管员id
			warehouseAdministrator2Id:'',
			inBoundQuantity: 0, //入库数量
			location: '', //存储位置
			providerId: '', //供应商id
			businessType: '', //业务类型
			inOrOut: 1,
			productBatchId: '', //productBatchId
			BoundOrderId: 0, //入库订单id
		});

		const queryForm = reactive({
			BusinessType: null,
			// WarehouseAdministrator: '',
			ChemisName: '',
			ChemicalId: null,
		});

		const resetClick = () => {
			searInfo.value = {};
			let newObj = Object.keys(searchObj);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = '';
					// console.log(i);
				});
			}
			initInfoFun();
		};

		const ruleFormRef = ref();
		const rules: any = reactive({
			chemicalId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			boundDate: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			providerId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			warehouseAdministratorId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			warehouseAdministrator2Id: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			inBoundQuantity: [
				{ required: true, message: '内容不能为空', trigger: 'blur' },
				{ pattern: /^[1-9]\d*$/, message: '请输入数字', trigger: 'blur' },
			],
			location: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			businessType: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			productBatchId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
		});

		/***** searchClick 查询按钮 *****/
		const searchClick = () => {
			let newObj = Object.keys(searInfo.value);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = searInfo.value[i];
				});
			}
		};

		/*** nodeClick 新增/编辑点击事件 */
		const options4: any = ref([]);
		const options1: any = ref([]);
		const saveId = ref();
		const nodeClick = async (obj: any) => {
			console.log(obj);

			if (obj.n_Id) {
				saveId.value = obj.n_Id;
				options2.value = [];
				let arr: any = {};
				dataTree.value.forEach((item: any) => {
					item.regions.forEach((i: any) => {
						console.log(i, obj, 'i');
						if (i.region == obj.location) {
							console.log(item, 'item');
							arr = item;
							item.regions.forEach((i: any) => {
								options2.value.push({
									label: i.locationName,
									value: i.region,
								});
							});
						} else {
							return (arr = []);
						}
					});
				});

				ruleForm.chemicalId = obj.chemicalId;
				ruleForm.boundDate = dayjs(obj.boundDate).format('YYYY-MM-DD');
				// ruleForm.warehouseAdministrator = obj.warehouseAdministrator;
				ruleForm.warehouseAdministratorId = obj.warehouseAdministratorId;
				ruleForm.warehouseAdministrator2Id = obj.warehouseAdministrator2Id;
				ruleForm.inBoundQuantity = obj.inBoundQuantity;
				ruleForm.location = String(obj.location);
				ruleForm.providerId = obj.providerId;
				ruleForm.businessType = obj.businessType;
				ruleForm.BoundOrderId = obj.BoundOrderId;
				ruleForm.productBatchId = obj.productBatchId;
			} else {
				queryStocksDangerousChemicalsInApi().then((res: any) => {
					console.log(res);
					ruleForm.BoundOrderId = res.data;
				});
			}
			showDialogVisible.value = true;
		};

		/*** cancelUseClick 取消事件 */
		const cancelUseClick = () => {
			ruleFormRef.value?.clearValidate();
			showDialogVisible.value = false;
			ruleForm.chemicalId = '';
			ruleForm.boundDate = '';
			// ruleForm.warehouseAdministrator = '';
			ruleForm.warehouseAdministratorId = '';
			ruleForm.warehouseAdministrator2Id = '';
			ruleForm.inBoundQuantity = 0;
			ruleForm.location = '';
			ruleForm.providerId = '';
			ruleForm.businessType = '';
			ruleForm.inOrOut = 1;
			saveId.value = '';
			ruleForm.productBatchId = ''; //产品id
			ruleForm.BoundOrderId = 0; //入库订单id
			fileData.value = [];
		};

		const options2: any = ref([]);
		const changeFun1 = (val: number) => {
			options2.value = [];
			dataTree.value.forEach((item: any) => {
				if (item.n_Id === val) {
					if (item.regions.length) {
						item.regions.forEach((i: any) => {
							options2.value.push({
								label: i.locationName,
								value: i.region,
							});
						});
					} else {
						options2.value = [];
					}
				}
			});
		};

		/*** controlUseClick 提交事件 */
		const controlUseClick = async (formEl: FormInstance | undefined, updateFun: Function) => {
			if (!formEl) return;
			await formEl.validate((valid, fields) => {
				if (valid) {
					console.log('submit!');
					if (saveId.value) {
						const obj = Object.assign({ ...ruleForm, id: saveId.value });
						updateStocksDangerousChemicalsInApi(obj).then((res) => {
							cancelUseClick();
							updateFun();
						});
					} else {
						addPutDangerousChemicalsInApi(ruleForm).then((res) => {
							cancelUseClick();
							updateFun();
						});
					}
				} else {
					console.log('error submit!', fields);
				}
			});
		};

		/*** deleteHandle 删除数据事件 */
		const deleteHandle = async (val: String | Number, updateFun: Function) => {
			ElMessageBox.confirm('请确定删除此条数据', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					let param = { id: val };
					try {
						let res: any = await deleteStocksDangerousChemicalsInApi(param);
						if (res.success) {
							updateFun();
						}
					} catch (err) {
						return;
					}
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '删除失败',
					});
				});
		};

		/*** 初始化数据 */
		const basicsInfo: any = ref([]);
		const initInfoFun = () => {
			basicsInfo.value = [
				{
					typeId: 'value', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'BusinessType', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '业务类型', // placeholder数据
					defaultProp: options4.value, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
				{
					typeId: 'name', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'ChemisName', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '危化品名称', // placeholder数据
					defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
				{
					typeId: 'warehouseAdministrator', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'WarehouseAdministrator', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '仓管员姓名', // placeholder数据
					defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
				{
					typeId: 'v_ProvideName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'ProviderName', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '友商名称', // placeholder数据
					defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
			];
		};

		const searInfo: any = ref();
		const searchHandel = (val: any) => {
			searInfo.value = val;
		};

		// token 键定义
		const accessTokenKey = 'access-token';

		// 获取 token
		const accessToken = Local.get(accessTokenKey);
		function authenticatedFetch(url:any, options:any = {}) {
			const headers = new Headers(options.headers || {});
			headers.set('Authorization', `Bearer ${accessToken}`); // 这里假设是Bearer类型的token

			const fetchOptions = {
				...options,
				headers,
			};

			return fetch(url, fetchOptions)
				.then((response) => {
					if (!response.ok) {
						throw new Error(`Request failed with status: ${response.status}`);
					}
					return response.json();
				})
				.catch((error) => {
					console.error('Authenticated fetch error:', error);
					throw error;
				});
		}

		let dataTree: any = ref([]);
		const options5: any = ref([]);
		const options6: any = ref([]);
		onMounted(async () => {
			// 获取字典4
			const res4 = await sysDictDataList({ TypeCode: 'InBound_BusinessType' });
			res4.data.forEach((element: any) => {
				options4.value.push({ label: element.value, value: element.id });
			});

			// 获取危化品1 queryStocksDangerousChemicalsInApi1
			const res1 = await queryStocksDangerousChemicalsInApi1();
			dataTree.value = res1.data;
			console.log(res1.data);
			res1.data.forEach((element: any) => {
				options1.value.push({ label: element.name, value: element.n_Id });
			});

			await initInfoFun();

			const res5 = await getChemicalsCargoManagerApi({ PosCode: 'WHPCGY' });
			options5.value = res5.data.map((item: any) => {
				return {
					label: item.name,
					value: item.id,
				};
			});

			const res6 = await authenticatedFetch('http://8.129.209.198:39054/OMS/ProviderV2/QueryList');
			options6.value = res6.data.map((item: any) => {
				return {
					label: item.v_ProvideName,
					value: item.n_Id,
				};
			});
		});

		/*** 截取日期格式方法 */
		const formatDate = (row: any, column: any) => {
			// 获取单元格数据
			let data = row[column.property];
			if (data == null) {
				return '-';
			}
			if (data === '1900-01-01 00:00:00') {
				return '-';
			}
			let dt = new Date(data);
			let month = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
			let date = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
			return dt.getFullYear() + '-' + month + '-' + date;
		};

		/*** ================================= 导出数据函数操作 ================================= */
		const excelRef: any = ref(null);
		const handleExport = () => {
			if (excelRef.value) {
				if (excelRef.value.data.length !== 0) {
					let tableExcel: any = [];
					let tableArr = excelRef.value.data;
					tableArr.map((item: any) => {
						let tableObj: any = {};
						tableObj['业务类型'] = item.value ? item.value : '-';
						tableObj['危化品名称'] = item.name ? item.name : '-';
						tableObj['友商名称'] = item.v_ProvideName ? item.v_ProvideName : '-';
						tableObj['仓管员姓名1'] = item.empName ? item.empName : '-';
						tableObj['仓管员姓名2'] = item.empName2 ? item.empName2 : '-';
						tableObj['状态'] = item.inOrOut == 1 ? '在库' : '出库';
						// tableObj['入库单号'] = item.BoundOrderId ? item.BoundOrderId : '-';

						tableObj['产品批号'] = item.productBatchId ? item.productBatchId : '-';
						tableObj['入库数量'] = item.inBoundQuantity ? item.inBoundQuantity : '-';
						tableObj['存储位置'] = item.locationDetailName ? item.locationDetailName : '-';
						tableObj['入库日期'] = item.boundDate ? item.boundDate : '-';

						tableExcel.push(tableObj);
					});
					exportToExcel(tableExcel, '危化品入库.xlsx');
				} else {
					ElMessage({
						type: 'error',
						message: '暂无数据导出',
					});
				}
			}
		};

		/*** viewClick 文件预览 */
const baseUrl = import.meta.env.VITE_API_URL;
const ideView = import.meta.env.VITE_APP_API_VIEW_IDE;
const viewClick = async (val: any) => {
	let viewUrl = baseUrl + '/' + val.path;
	console.log(viewUrl);
	window.open(viewUrl);
};

/*** downClick 下载文件 */
const downClick = async (val: any) => {
	let getFile = getFileFun(val.id);
	// 等待getFileFun完成
	await getFile;
	if (getFile && getFile.then) {
		getFile.then((res) => {
			let base64Data = res;
			let blob = base64ToBlob(base64Data);

			// 创建可下载的链接
			let url = URL.createObjectURL(blob);
			let link = document.createElement('a');
			link.href = url;
			link.download = val.fileOriginName; // 指定下载的文件名

			// 将链接添加到DOM中
			document.body.appendChild(link);

			// 触发点击事件开始下载
			link.click();

			// 释放临时URL
			URL.revokeObjectURL(url);
		});
	}
};
/*** getFileFun 获取文件数据 */
const getFileFun = async (val: Number) => {
	let param: any = {};
	param.id = val;
	let res: any = await sysFileInfoPreviewBase64(param);
	console.log(res, 'res');
	if (res.success) {
		return res.data;
	}
};
// 将Base64编码数据转换为Blob对象的辅助函数
const base64ToBlob = (base64Data: any) => {
	var byteString = atob(base64Data.split(',')[1]); // 提取Base64编码的数据部分
	var mimeString = base64Data.split(':')[1].split(';')[0]; // 提取MIME类型
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], { type: mimeString });
};

/*** delClick 删除文件事件 */
const delClick = async (val: Number) => {
	console.log(val, 'val');
	let param: any = {};
	param.id = val;
	await sysFileInfoDelete(param);
	await selectProviderId(ruleForm.providerId)
	// await searchClick();
	// if (res.success) {
	//     getPageFile(JSON.parse(props.fileInfo).sourceId);
	// }
};

const selectProviderId = async (id:any) => {
	const res = await downloadFileApi({providerId:id});
	fileData.value = [];
	res.data.rows.forEach((item: any) => {
		item.v_FilePath.forEach((i: any) => {
			i.name = item.documentName;
			fileData.value.push(i);
		});
	});
	console.log(fileData.value, 'fileData');
}


		return {
			...getTableData(getStocksDangerousChemicalsInApi, {}, searchObj),
			cancelUseClick,
			controlUseClick,
			nodeClick,
			deleteHandle,
			searchClick,
			transferVal,
			/***/
			showDialogVisible,
			ruleForm,
			options1,
			saveId,
			rules,
			options4,
			ruleFormRef,
			queryForm,
			resetClick,
			dataTree,
			changeFun1,
			options2,
			searchHandel,
			basicsInfo,
			formatDate,
			handleExport,
			excelRef,
			options5,
			options6,
			fileData,viewClick,downClick,delClick,selectProviderId
		};
	},
});
</script>
<style lang="scss">
@import '../style/public.scss';
</style>
<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
